package com.gr.experimental.model.impl.distr.operations;

import com.gr.experimental.model.RVClass;
import com.gr.experimental.model.impl.distr.Context;
import com.gr.experimental.model.impl.distr.Descriptor;
import com.gr.experimental.model.impl.distr.DescriptorType;

public class CountRVClassFunction extends AbstractFunction {

	public CountRVClassFunction() {
		super("count", Integer.class, new Class<?>[] {RVClass.class}, true);
	}

	@Override
	public Object invoke(Context ctx, Object[] parameters) {
		assert ctx != null;
		assert parameters.length == 1;
		RVClass rvClass = (RVClass) parameters[0];
		assert rvClass != null;
		Descriptor descriptor = ctx.getDescriptor(rvClass.getName());
		assert descriptor != null;
		assert descriptor.getDescriptorType() == DescriptorType.RandomVariable;

		// we currently assume that the value is precomputed 
		// and put in the variable of form "count(X)"
		String symbolName = descriptor.getSymbolName();
		String countVarName = "count(" + symbolName + ")";
		Descriptor countVarDescriptor = ctx.getDescriptor(countVarName);
		if (countVarDescriptor == null) {
			return 0;
		}
		Object variableValue = ctx.getVariableValue(countVarName);
		assert variableValue instanceof Integer;
	    return variableValue;
	}

}
